package com.almond.mq.handle;

import com.almond.mq.config.RabbitMQConfig;
import com.almond.mq.constant.MqConstant;
import com.almond.mq.model.OrderNotifyMQ;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.UUID;

@Component
@Slf4j
public class AmqMessageHandle {
    @Resource
    private RabbitTemplate rabbitTemplate;

    public void orderMsg(Long notifyId, Integer delays) {
        OrderNotifyMQ orderNotifyMQ = OrderNotifyMQ.build(notifyId);
        String messageId = UUID.randomUUID().toString().replace("-", "");
        rabbitTemplate.convertAndSend(RabbitMQConfig.DELAYED_EXCHANGE_NAME, orderNotifyMQ.getMQName(), orderNotifyMQ.toMessage(), messagePostProcessor -> {
            messagePostProcessor.getMessageProperties().setDelay(Math.toIntExact(delays * 1000));
            messagePostProcessor.getMessageProperties().setMessageId(messageId);
            return messagePostProcessor;
        },new CorrelationData(messageId));
    }


    public void sendMsg(String message, String routingKey) {
//        MessageProperties messageProperties = new MessageProperties();
        String messageId = UUID.randomUUID().toString().replace("-", "");
        log.info("msgId{}",messageId);
//        messageProperties.setMessageId(messageId);
////        messageProperties.setCorrelationId(messageId);
//        Message amqpMessage = new Message(message.getBytes(), messageProperties);
//        amqpMessage.getMessageProperties().setCorrelationId(messageId);
        rabbitTemplate.convertAndSend("amq.topic", routingKey, message,new CorrelationData(messageId));

//        CorrelationData correlationData = new CorrelationData();
//        correlationData.setReturned(new ReturnedMessage(amqpMessage,1,"1","amq.topic",routingKey));
//
//        rabbitTemplate.convertAndSend(MqConstant.DEFAULT_EXCHANGE,routingKey,amqpMessage,correlationData);
    }

    public void sendDirectMsg(String message,String routingKey) {
        MessageProperties messageProperties = new MessageProperties();
        String messageId = UUID.randomUUID().toString().replace("-", "");
        log.info("msgId{}",messageId);
        messageProperties.setMessageId(messageId);
        Message amqpMessage = new Message(message.getBytes(), messageProperties);
//        rabbitTemplate.convertAndSend("amq.topic", routingKey, amqpMessage);

        CorrelationData correlationData = new CorrelationData();
        correlationData.setReturned(new ReturnedMessage(amqpMessage,1,"1",MqConstant.DIRECT_EXCHANGE,routingKey));

        rabbitTemplate.convertAndSend(MqConstant.DIRECT_EXCHANGE,routingKey,amqpMessage,correlationData);
    }
}
